import os
from google.appengine.ext.webapp import template

import cgi

from google.appengine.api import users
from google.appengine.api import images
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail

class Car(db.Model):
  year = db.IntegerProperty()
  make = db.StringProperty()
  model = db.StringProperty()
  mileage = db.IntegerProperty()
  price = db.IntegerProperty()
  vinnumber = db.StringProperty()
  color = db.StringProperty()
  description = db.TextProperty() 
  
  poster = db.UserProperty()
  
  pic1 = db.BlobProperty()
  pic2 = db.BlobProperty()
  pic3 = db.BlobProperty()
  pic4 = db.BlobProperty()
  pic5 = db.BlobProperty()
  pic6 = db.BlobProperty()
  pic7 = db.BlobProperty()
  pic8 = db.BlobProperty()
  pic9 = db.BlobProperty()
  pic10 = db.BlobProperty()
  active = db.BooleanProperty()
  

class MainPage(webapp.RequestHandler):
  def get(self):
    
    cars_query = db.GqlQuery("SELECT * FROM Car WHERE active=True ORDER BY year");
    
    cars = cars_query.fetch(1000)

    if(users.is_current_user_admin()):
        isAdmin = True
    else:
        isAdmin = False
        
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    page = self.request.get('page');

    if(page == ""):
        page = "home";
    
    template_values = {
      'cars': cars,
      'url': url,
      'url_linktext': url_linktext,
      'page': page + ".html",
      'isAdmin': isAdmin,
      }

    path = os.path.join(os.path.dirname(__file__), 'main.html')
    self.response.out.write(template.render(path, template_values))

class DetailsCar(webapp.RequestHandler):
  def get(self):
    carkey = self.request.get('carkey');
    car = Car.get(carkey);
    
    if(users.is_current_user_admin()):
        isAdmin = True
    else:
        isAdmin = False
        
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login Now'
      
    page = self.request.get('page');
    if(page == ""):
        page = "home";
    
    template_values = {
      'car': car,
      'url': url,
      'url_linktext': url_linktext,
      'page': page + ".html",
      'isAdmin': isAdmin,
      }

    path = os.path.join(os.path.dirname(__file__), 'main.html')
    self.response.out.write(template.render(path, template_values))


class AddCar(webapp.RequestHandler):
    def post(self):
        car = Car();

        car.active = True;
        car.year = (int)(self.request.get('year'))
        car.make = self.request.get('make')
        car.model = self.request.get('model')
        car.mileage = (int)(self.request.get('mileage'))
        car.price = (int)(self.request.get('price'))
        car.vinnumber = self.request.get('vinnumber')
        car.color = self.request.get('color')
        car.description = self.request.get('description').replace("\n", "<br />\n")
        car.poster = users.get_current_user()
        
        h = 500;
        w = 500;
        
        if self.request.get('pic1'):
            img1 = images.Image(self.request.get('pic1'));
            img1.resize(width=w, height=h);
            pic1 = img1.execute_transforms(output_encoding=images.JPEG);
            car.pic1 = db.Blob(pic1);
        
        if self.request.get('pic2'):
            img2 = images.Image(self.request.get('pic2'));
            img2.resize(width=w, height=h);
            pic2 = img2.execute_transforms(output_encoding=images.JPEG);
            car.pic2 = db.Blob(pic2);
        
        if self.request.get('pic3'):
            img3 = images.Image(self.request.get('pic3'));
            img3.resize(width=w, height=h);
            pic3 = img3.execute_transforms(output_encoding=images.JPEG);
            car.pic3 = db.Blob(pic3);

        if self.request.get('pic4'):
            img4 = images.Image(self.request.get('pic4'));
            img4.resize(width=w, height=h);
            pic4 = img4.execute_transforms(output_encoding=images.JPEG);
            car.pic4 = db.Blob(pic4);
        
        if self.request.get('pic5'):
            img5 = images.Image(self.request.get('pic5'));
            img5.resize(width=w, height=h);
            pic5 = img5.execute_transforms(output_encoding=images.JPEG);
            car.pic5 = db.Blob(pic5);
        
        if self.request.get('pic6'):
            img6 = images.Image(self.request.get('pic6'));
            img6.resize(width=w, height=h);
            pic6 = img6.execute_transforms(output_encoding=images.JPEG);
            car.pic6 = db.Blob(pic6);
        
        if self.request.get('pic7'):
            img7 = images.Image(self.request.get('pic7'));
            img7.resize(width=w, height=h);
            pic7 = img7.execute_transforms(output_encoding=images.JPEG);
            car.pic7 = db.Blob(pic7);
        
        if self.request.get('pic8'):
            img8 = images.Image(self.request.get('pic8'));
            img8.resize(width=w, height=h);
            pic8 = img8.execute_transforms(output_encoding=images.JPEG);
            car.pic8 = db.Blob(pic8);
        
        if self.request.get('pic9'):
            img9 = images.Image(self.request.get('pic9'));
            img9.resize(width=w, height=h);
            pic9 = img9.execute_transforms(output_encoding=images.JPEG);
            car.pic9 = db.Blob(pic9);
        
        if self.request.get('pic10'):
            img10 = images.Image(self.request.get('pic10'));
            img10.resize(width=w, height=h);
            pic10 = img10.execute_transforms(output_encoding=images.JPEG);
            car.pic10 = db.Blob(pic10);
        
        
        car.put();

        self.redirect('/?page=cars_overview');

class RemoveCar(webapp.RequestHandler):
    def get(self):
        carkey = self.request.get('carkey');
        car = Car.get(carkey)
        car.active = False;
        car.put();

        self.redirect('/?page=cars_overview');

class Image (webapp.RequestHandler):
  def get(self):
    car = db.get(self.request.get("carkey"))
    whichpic = (int)(self.request.get("whichpic"));
    
    if car.pic1:
      self.response.headers['Content-Type'] = "image/png"
      if(whichpic == 1):
          self.response.out.write(car.pic1)
      elif (whichpic == 2):
          self.response.out.write(car.pic2)
      elif (whichpic == 3):
          self.response.out.write(car.pic3)
      elif (whichpic == 4):
          self.response.out.write(car.pic4)
      elif (whichpic == 5):
          self.response.out.write(car.pic5)
      elif (whichpic == 6):
          self.response.out.write(car.pic6)
      elif (whichpic == 7):
          self.response.out.write(car.pic7)
      elif (whichpic == 8):
          self.response.out.write(car.pic8)
      elif (whichpic == 9):
          self.response.out.write(car.pic9)
      elif (whichpic == 10):
          self.response.out.write(car.pic10)
      # ... elif 2, 3, etc
    else:
      self.error(404)

class ContactToBuy (webapp.RequestHandler):
  def post(self):
    
    sender = self.request.get('email')
    subject = "[UsaDubaiCarSales] " + self.request.get('subject')
    body = "Car URL: " + self.request.get('car_url') + "\n\nName: " + self.request.get('yourname') + "\n\nEmail: " + self.request.get('email') + "\n\nPhone number " + self.request.get('phone') + "\n\nTheir message: \n" + self.request.get('other_requests')
    
    emailaddys = ["farouksm@aol.com", "ahmemon@gmail.com", "farouksm@gmail.com", "muneebam@gmail.com", "treguess@gmail.com"]
    
    if not mail.is_email_valid(sender):
        self.redirect('/?page=invalid_emailaddr')
    else:
        for addy in emailaddys:
            mail.send_mail("ahmemon@gmail.com", addy, subject, body, reply_to=sender)
        #mail.send_mail("ahmemon@gmail.com", "farouksm@gmail.com", subject, body, reply_to=sender)
        self.redirect('/?page=thankyou')

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/img', Image),
                                      ('/addcar', AddCar),
                                      ('/removecar', RemoveCar),
                                      ('/car_details', DetailsCar),
                                      ('/contact_to_buy', ContactToBuy)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
